﻿//获取url参数的值
function GetRequestURL(key) {
    var url = location.search;
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            if (strs[i].split("=")[0].toLocaleLowerCase() == key.toLocaleLowerCase()) {
                return strs[i].split("=")[1];
            }
        }
    }
    return "";
}

//请求失败错误信息处理 成功返回 true 否则为false
function RequestErrorHelper(data) {
    if (!data.IsSuccess) {
        if (data.code == 101) {
            top.layer.alert(data.msg, { icon: 0 }, function () {
                top.location.replace('/Admin/Login.aspx');
            })
        }
        else
            top.layer.alert(data.msg);
        return false;
    }
    else
        return true;
}

//同步:获取对象信息-控制器-方法名-参数
function GetObjectInfoFunction(funName, Data, act) {
    //var result = null;
    $.ajax({
        url: bootPATH + funName,
        data: Data,
        type: "post",
        async: false,
        success: function (JData) {
            //result = JData;
            top.layer.closeAll('loading'); //关闭加载层
            var data = JSON.parse(JData);
            if (RequestErrorHelper(data))
                act(data);
        },
        error: function (jqXHR) {
            top.layer.closeAll('loading'); //关闭加载层
            if (jqXHR.responseText != "")
                top.layer.alert(jqXHR.responseText);
        }
    });
    //return result;
}

//异步:获取对象信息-控制器-方法名-参数-无弹窗
function GetObjectInfoFunction_Async(funName, Data, act) {
    $.ajax({
        url: bootPATH + funName,
        data: Data,
        type: "post",
        async: true,
        success: function (JData) {
            top.layer.closeAll('loading'); //关闭加载层
            var data = JSON.parse(JData);
            if (RequestErrorHelper(data))
                act(data);
        },
        error: function (jqXHR) {
            top.layer.closeAll('loading'); //关闭加载层
            top.layer.alert(jqXHR);
        }
    });
}

//判断字符串是否为空
function StringIsNullOrEmpty(str) {
    if (str == null)
        return true;
    if ($.trim(str) == "")
        return true;
    return false;
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date(),"yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date(),"yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
function DateToString(obj, strFormat) {

    strFormat = strFormat || 'yyyy-MM-dd HH:mm:ss';
    if (obj == null || obj == "")
        return "";
    if (typeof (obj) == "string") {
        var ary = obj.replace(/T/g, " ").replace(/-/g, "/").split('.');
        obj = new Date(ary[0]);
    }

    var o = {
        "M+": obj.getMonth() + 1, //月份
        "d+": obj.getDate(), //日
        "h+": obj.getHours(), //小时
        "H+": obj.getHours(), //小时
        "m+": obj.getMinutes(), //分
        "s+": obj.getSeconds(), //秒
        "q+": Math.floor((obj.getMonth() + 3) / 3), //季度
        "S": obj.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(strFormat)) strFormat = strFormat.replace(RegExp.$1, (obj.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(strFormat)) strFormat = strFormat.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return strFormat;
}

//乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：accMul(arg1,arg2)
//返回值：arg1乘以arg2的精确结果
function accMul(arg1, arg2) {
    if (StringIsNullOrEmpty(arg1))
        arg1 = 0;
    if (StringIsNullOrEmpty(arg2))
        arg2 = 0;
    var m = 0, s1 = $.trim(arg1.toString()), s2 = $.trim(arg2.toString());
    try { m += s1.split(".")[1].length } catch (e) { }
    try { m += s2.split(".")[1].length } catch (e) { }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
}

//除法函数，用来得到精确的除法结果
//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
//调用：accDiv(arg1,arg2)
//返回值：arg1除以arg2的精确结果
function accDiv(arg1, arg2) {
    if (StringIsNullOrEmpty(arg1))
        arg1 = 0;
    if (StringIsNullOrEmpty(arg2))
        arg2 = 0;
    if (arg2 == null || arg2 == 0)
        return 0;
    var t1 = 0, t2 = 0, r1, r2;
    try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
    try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""))
        r2 = Number(arg2.toString().replace(".", ""))
        var rVal = (r1 / r2) * pow(10, t2 - t1);
        return rVal;
    }
}

//加法函数，用来得到精确的加法结果
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
//调用：accAdd(arg1,arg2)
//返回值：arg1加上arg2的精确结果
function accAdd(arg1, arg2) {
    if (StringIsNullOrEmpty(arg1))
        arg1 = 0;
    if (StringIsNullOrEmpty(arg2))
        arg2 = 0;
    var r1, r2, m;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2))
    var result = (arg1 * m + arg2 * m) / m;

    return parseFloat(result);
}

//减法函数，用来得到精确的减法结果
function accSub(arg1, arg2) {
    if (StringIsNullOrEmpty(arg1))
        arg1 = 0;
    if (StringIsNullOrEmpty(arg2))
        arg2 = 0;
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//更新对象值,obj2中属性的值覆盖obj1
function UpdateJson(obj1, obj2) {
    for (var key in obj2) {
        if (obj2[key] != null) {
            if (typeof (obj2[key]) == "function") {
                continue;
            }

            if (typeof (obj2[key]) == "object") {
                if (JSON.stringify(obj2[key])[0] == '[') {
                    obj1[key] = [];
                }
                else if (obj1[key] == null) {
                    obj1[key] = {};
                }
                UpdateJson(obj1[key], obj2[key]);
            }
            else
                obj1[key] = obj2[key];
        }
    }
}

/** 
 * 抹零方式 
 * 0：不抹零, 1：四舍五入（元）,2：逢一进十（元）,3：舍位取整（元） 
 * 4：四舍五入（角）,5：逢一进十（角）,6：舍位取整（角）
 * 7：四舍五入（分）,8：逢一进十（分） ,9：舍位取整（分） 
 * 10：四舍五入（十元）,11：逢一进十（分）,12：舍位取整（十元）
 */
function RoundWay(val, roundWay) {
    var x = val;
    var scal = 1; //精确小数位  
    var accuracy = Math.pow(10, scal);
    switch (roundWay) {
        case 0:
            return 0;
            break;
        case 1:
            return Math.round(x);
            break;
        case 2:
            return Math.ceil(x);
            break;
        case 3:
            return Math.floor(x);
            break;
        case 4:
            x = Math.round(accMul(x, accuracy));
            return accDiv(x, accuracy);
            break;
        case 5:
            x = Math.round(accMul(x, accuracy));
            return accDiv(x, accuracy);
            break;
        case 6:
            x = Math.round(accMul(x, accuracy));
            return accDiv(x, accuracy);
            break;
        case 7:
            scal = 2; //精确小数位  
            accuracy = Math.pow(10, scal);
            x = Math.round(accMul(x, accuracy));
            return accDiv(x, accuracy);
            break;
        case 8:
            scal = 2; //精确小数位  
            accuracy = Math.pow(10, scal);
            x = Math.round(accMul(x, accuracy));
            return accDiv(x, accuracy);
            break;
        case 9:
            scal = 2; //精确小数位  
            accuracy = Math.pow(10, scal);
            x = Math.round(accMul(x, accuracy));
            return accDiv(x, accuracy);
            break;
        case 10:
            x = accDiv(x, 10);
            x = RoundWay(x, 1);
            x = accMul(x, 10);
            return x;
            break;
        case 11:
            x = accDiv(x, 10);
            x = RoundWay(x, 2);
            x = accMul(x, 10);
            return x;
            break;
        case 12:
            x = accDiv(x, 10);
            x = RoundWay(x, 3);
            x = accMul(x, 10);
            return x;
            break;
        default:
            return 0;
            break;
    }
}

//对象深拷贝
function objDeepCopy(source) {
    var sourceCopy = source instanceof Array ? [] : {};
    for (var item in source) {
        if (source[item] == null)
            sourceCopy[item] = source[item];
        else
            sourceCopy[item] = typeof source[item] === 'object' ? objDeepCopy(source[item]) : source[item];
    }
    return sourceCopy;
}

//更新对象值,obj2中属性的值覆盖obj1
function UpdateJson(obj1, obj2) {
    for (var key in obj2) {
        if (obj2[key] != null) {
            if (typeof (obj2[key]) == "function") {
                continue;
            }

            if (typeof (obj2[key]) == "object") {
                if (JSON.stringify(obj2[key])[0] == '[') {
                    obj1[key] = [];
                }
                else if (obj1[key] == null) {
                    obj1[key] = {};
                }
                UpdateJson(obj1[key], obj2[key]);
            }
            else
                obj1[key] = obj2[key];
        }
    }
}

//获取form查询条件列表
function getFilter(data, where) {
    if (where == null || where == "undefined")
        where = [];
    for (var key in data.field) {
        if (!StringIsNullOrEmpty(data.field[key])) {
            var item = data.form.elements[key].getAttribute("data-options");
            var itemOptions = data.form.elements[key].dataset.options;

            if (itemOptions) {
                itemOptions = JSON.parse(itemOptions);
                var subLogic = "";
                if (!StringIsNullOrEmpty(itemOptions.SubLogic))
                    subLogic = itemOptions.SubLogic;
                var IsNoSubField = false;
                if (itemOptions.IsNoSubField == "true")
                    IsNoSubField = true;
                where.push({ Field: itemOptions.Field, Value: data.field[key], SubLogic: subLogic, Logic: itemOptions.Logic, Method: itemOptions.Method, IsNoSubField: IsNoSubField });
            }
        }
    }

    return JSON.stringify(where);
}